package bll

import (
	"context"
	"maya-service/store/mysql"

	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/model/mapping"
	"maya-service/store"
	"time"
)

type orderGrab struct {
	iOrderGrab store.IOrderGrab
}

var OrderGrab = &orderGrab{
	iOrderGrab: mysql.OrderGrab,
}

func init() {
	Register(OrderGrab)
}

func (a *orderGrab) init() func() {
	return func() {}
}

// Create
func (a *orderGrab) Create(ctx context.Context, in *model.OrderGrabCreateRequest) error {
	var (
		err error
	)
	c := buildOrderGrab(in)
	_, err = a.iOrderGrab.Create(ctx, c)
	return err
}

// Update
func (a *orderGrab) Update(ctx context.Context, in *model.OrderGrabUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.OrderId != nil {
		dict["order_id"] = in.OrderId
	}

	if in.UserId != nil {
		dict["user_id"] = in.UserId
	}

	if in.GrabTime != nil {
		dict["grab_time"] = in.GrabTime
	}

	if in.Status != nil {
		dict["status"] = in.Status
	}

	if in.CreatedAt != nil {
		dict["created_at"] = in.CreatedAt
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	return a.iOrderGrab.Update(ctx, in.Id, dict)
}

// Delete
func (a *orderGrab) Delete(ctx context.Context, in *model.OrderGrabDeleteRequest) error {
	return a.iOrderGrab.Delete(ctx, in.Id)
}

// List
func (a *orderGrab) List(ctx context.Context, in *model.OrderGrabListRequest) (*model.OrderGrabListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.OrderGrab
		out   = &model.OrderGrabListResponse{}
	)

	if total, list, err = a.iOrderGrab.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = mapping.OrderGrabsEntityToDto(list)

	return out, nil
}

// Find
func (a *orderGrab) Find(ctx context.Context, in *model.OrderGrabInfoRequest) (*model.OrderGrabInfo, error) {
	var (
		err  error
		data *entity.OrderGrab
		out  = &model.OrderGrabInfo{}
	)

	if data, err = a.iOrderGrab.Find(ctx, in); err != nil {
		return nil, err
	}

	out = mapping.OrderGrabEntityToDto(data)
	return out, nil
}

// buildOrderGrab build entity
func buildOrderGrab(in *model.OrderGrabCreateRequest) *entity.OrderGrab {

	ety := &entity.OrderGrab{}

	ety.OrderId = in.OrderId

	ety.GrabTime = in.GrabTime

	ety.Status = in.Status

	ety.UserId = in.UserId

	ety.CreatedAt = time.Now().Unix()

	ety.UpdatedAt = in.UpdatedAt

	return ety
}
